#include "constants.h"
#include "macros.sqf"
// by Xeno
// Commented/Edited by Tyrghen

private ["_i", "_mrkr", "_str", "_pos", "_nobjs", "_box", "_pod", "_weapp", "_magp", "_res", "_taskstr", "_objstatus", "_no", "_color", "_xres", "_winner", "_counterxx", "_text", "_mcol", "_boxnew", "_boxscript", "_scriptarti", "_scriptdrop", "_callvecari1", "_callvecari2", "_callvecdrop", "_script", "_artinum", "_s", "_id", "_trigger", "_types", "_action", "_ar", "_pc", "_element", "_dir", "_fac", "_tactionar", "_boxname", "_aiunitslist", "_one", "_primw", "_muzzles"];

// We wait that the player is initialized.
waitUntil {!isnil "X_INIT"};
waitUntil {X_INIT && X_LOADED};
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3: %4",diag_tickTime,"Setupplayer.sqf","Starting execution for",str(player)]; };

sleep 2;

g_sPlayerName = name player;
g_sPlayerFaction = faction player;
g_oGroupCaller = objNull;

// This vehicle is used to store some vars we want to keep in a tight place.
g_oVariableStorage = "HeliHEmpty" createVehicleLocal [0,0,0];

// When setting in the variables of a unit this variable to true, the unit won't begin to babble senselessly.
// Extremely useful on AI units.
player setVariable ["BIS_noCoreConversations", true];

// Get the name of the player defined in the "Name" field of the unit. This name is very very very important since it defines
// the special abilities of the player. In i_client.sqf you have several arrays linking the player with the functionnalities
d_string_player = str(player);

d_player_spawn_started = true;

If (d_revive_script == "R3F") then {
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Using R3F Revive"]; };
	execVM "scripts\R3F_revive\revive_init.sqf";
};

d_flag_vec = objNull;

if (isNil "g_bCommonFuncsCompiled") then {
	__cppfln(XCreateWeaponArray,scripts\wpn_array.sqf);
	__ccppfln(common\functions\commonfunctions.sqf);
	__ccppfln(common\functions\netfunctions.sqf);
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 (mission:%4)",diag_tickTime,"Setupplayer.sqf","Compiled reloadvehicle.sqf, commonfunctions.sqf, netfunctions.sqf",! isnil "d_mission_functions_compiled"]; };
};
//__cppfln(x_weaponcargo,client\weaponcargo.sqf);
__cppfln(x_weaponcargo,client\weaponcargo2.sqf);
__ccppfln(client\functions\playerfunctions.sqf);
__ccppfln(client\functions\clientfunctions.sqf);
__ccppfln(client\functions\uifunctions.sqf);
__ccppfln(client\functions\netinitclient.sqf);
__cppfln(x_initvec,client\initvec.sqf);
__cppfln(bis_fnc_halo,scripts\AAHALO\Scripts\fn_halo.sqf);

if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Compiled weaponcargo, playerfunctions, clientfunctions, netiniclient, initvec"];};

__cppfln(x_checkhelipilot,client\checkhelipilot.sqf);
__cppfln(x_checkhelipilotout,client\checkhelipilotout.sqf);

// TODO: Try to reenable it.
//if (isNil "x_flares") then {__cppfln(x_flares,scripts\flares.sqf)};

// To understand the following, let's take the exemple below.
// In init.sqf, when the server starts (under "if (isServer)") we create a vehicle: X_Drop_Zone, which is an invisible helipad.
// This vehicle is thus accessible to everyone.
// When a player connects, this object is synched and is available, BUT, the scripts on the player computer don't have
// the handle to this object. Because it was created on the server only and only the server has a variable X_Drop_Zone.
// Thus... we place the handler as a variable of the JIP Variable Holder Empty helipad (see netfunctions.sqf) and
// we create the same global variable (X_Drop_Zone) on all clients. We then set the value of this.
if (!X_SPE) then {
	X_DropZone = (["X_DropZone",[]] call XNetGetJIP);
};

["dummy_marker", [0,0,0],"ICON","ColorBlack",[1,1],"",0,"Empty"] call XfCreateMarkerLocal;
["x_drop_zone", [0,0,0],"ICON","ColorBlue",[1,1],"Air Drop Zone",0,"mil_dot","",0.01] call XfCreateMarkerLocal;
"x_drop_zone" setMarkerPosLocal getPosASL X_DropZone;

If (!isNil("LHD_Center")) then {
	["LHD_Carrier", LHD_Center,"ICON","ColorBlue",[1,1],"LHD Carrier",0,"NATO_Base"] call XfCreateMarkerLocal;
	"LHD_Carrier" setMarkerPosLocal getPosASL LHD_Center;
};

[4, "d_dam", {(_this select 0) allowDamage (_this select 1)}] call XNetAddEvent;
[2, "d_m_box", {_this spawn XfCreateBoxNet}] call XNetAddEvent;
[2, "d_r_box", {_this spawn XfRemoveBoxNet}] call XNetAddEvent;
[2, "d_air_box", {_this spawn XfCreateAirBoxNet}] call XNetAddEvent;
[2, "d_ataxi", {_this spawn XfAirTaxiNet}] call XNetAddEvent;
[2, "d_n_v", {_this spawn x_initvec}] call XNetAddEvent;
[2, "d_mhqdepl", {_this spawn XfMHQdeplNet}] call XNetAddEvent;
[2, "d_s_p_inf", {d_u_r_inf = _this}] call XNetAddEvent;
[2, "d_w_ma", {deleteMarkerLocal _this}] call XNetAddEvent;
[2, "d_p_o_a", {
		private "_ar";_ar = _this select 1;
		// if ((_ar select 0) isKindOf "Mash") then {
			// [_ar select 1, position (_ar select 0),"ICON","ColorBlue",[0.5,0.5],format ["Mash %1", _ar select 2],0,"mil_dot"] call XfCreateMarkerLocal;
		// } else {
			// [_ar select 1, position (_ar select 0),"ICON","ColorBlue",[0.5,0.5],format ["MG Nest %1", _ar select 2],0,"mil_dot"] call XfCreateMarkerLocal;
		// };
		[_ar select 1, position (_ar select 0),"ICON","ColorBlue",[0.5,0.5],_ar select 4,0,"mil_dot"] call XfCreateMarkerLocal;
	}] call XNetAddEvent;
[2, "d_p_o_r", {deleteMarkerLocal (_this select 1)}] call XNetAddEvent;
[2, "d_dropansw", {_this spawn XfDropAnswer}] call XNetAddEvent;
[2, "d_p_o_an", {[] spawn XfPlacedObjAn}] call XNetAddEvent;
[2, "d_w_m_c", {[_this select 0, _this select 1,"ICON","ColorBlue",[1,1],format ["%1 wreck", _this select 2],0,"mil_triangle"] call XfCreateMarkerLocal}] call XNetAddEvent;
[2, "d_teleport", {_this spawn XfTeleport}] call XNetAddEvent;
// Calling this event will execute code on all player computers
[2, "d_p_exec", {_this spawn compile (_this select 0)}] call XNetAddEvent;
[2, "d_msg", { _this call XfHandleMessage}] call XNetAddEvent;
[2, "d_arty_trail", {_this spawn XfArtyShellTrail}] call XNetAddEvent;

if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Player events created"]; };

if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","calling Initvec"]; };
// Launch a treatment which will, for example add all markers for vehicles
// If you are a JIP player, then you didn't receive the d_n_v Events for the addition of new vehicle/markers.
// See initvec.sqf for more details.
[] spawn {
	sleep 2;
	{_x call x_initvec;sleep 0.01} forEach vehicles;
};

// TODO: Enable back and check the scripts
// Creates a HUD which gives the direction in which the vehicle is going... helpful
if (WithVecHud) then {execVM "client\vec_hud.sqf"};
// Creates a HUD which gives the direction in which the vehicle is going... helpful
if (WithChopHud) then {execVM "client\chop_hud.sqf"};

if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Invoking PlayerAmmoBox.sqf"]; };
// This will create and fill the ammobox at the base. Plus it will refill it from time to time when the player comes back to take stuffs.
[] spawn compile preprocessFileLineNumbers "client\playerammobox.sqf";

// We add some standard stuff to the player like NV, Binocular and GPS
#define __paddweap(xweap) if (!(player hasWeapon #xweap)) then {player addWeapon #xweap}
__paddweap(NVGoggles);
__paddweap(Binocular);
__paddweap(ItemGPS);

// We automatically equip the NV if the time of the day is right.
if (daytime > 17.5 || daytime < 6.25) then {player action ["NVGoggles",player]};

__cppfln(x_playerspawn,client\playerspawn.sqf);
__cppfln(x_checkkill,client\checkkill.sqf);
__cppfln(XfHandleDamage,client\handle_damage.sqf);
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Compiled playerspawn.sqf and checkkill.sqf"]; };

player addEventHandler ["killed", {_this spawn x_checkkill; player setVariable ["DamageChart",[[],[]]];}];
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","CheckKill event handler added"]; };
player setVariable ["DamageChart",[[],[]]];
player addEventHandler ["HandleDamage", {_this call XfHandleDamage}];

// If there are already ammoboxes created around the world, we add them to the local vehicles for the player
if (count (["d_ammo_boxes",[]] call XNetGetJIP) > 0) then {
	private ["_ammo_boxes","_box_pos","_vec"];
	_ammo_boxes = (["d_ammo_boxes",[]] call XNetGetJIP);
	(["d_ammo_boxes",[]] call XNetGetJIP) spawn {
		private "_ammo_boxes";
		_ammo_boxes = _this;
		{
			if (typeName _x == "ARRAY") then {
				_box_pos = _x select 0;
				If ( count _box_pos == 3 ) then {
					// _box_side = d_own_side;
					// _box_type = d_default_ammo_box;
					// if ((_x select 2) != "") then {[(_x select 2), _box_pos,"ICON","ColorBlue",[0.5,0.5],"",0,"mil_marker"] call XfCreateMarkerLocal};
					// if (count _x > 3) then {_box_side = _x select 3;};
					// if (count _x > 4) then {_box_type = _x select 4;};
					// To correct the problem of air dropped boxes which sometimes are recorded as above ground.
					_box_pos = [_box_pos select 0, _box_pos select 1, 0];
					_x set [0,_box_pos];
					// We use the netinitclient function in order to avoid duplication code.
					_x spawn XfCreateBoxNet;
					// _boxnew = _box_type createVehicleLocal _box_pos;
					// _marker_name=Format["box%1%2%3",floor(_box_pos select 0),floor(_box_pos select 1),floor(_box_pos select 2)];
					// _boxnew setVariable ["map_marker", _marker_name];
					// [_marker_name, _box_pos, "ICON", "ColorBlack", [0.6,0.6],"",0,"marker","",0.5] call XfCreateMarkerLocal;
					// _boxnew setPos _box_pos;
					// [_boxnew,_box_side] spawn x_weaponcargo;
					// _boxnew addEventHandler ["killed",{["d_r_box", position _this select 0] call XNetCallEvent;deleteVehicle (_this select 0)}];
					if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3: %4,%5 (%6)",diag_tickTime,"Setupplayer.sqf","Adding Ammo",_box_type,_box_side,_box_pos]; };
				};
			};
		} forEach _ammo_boxes;
	};
};

d_player_can_call_drop = false;
d_player_busy_building = false;
d_player_can_rescue = false;

if ((d_string_player in d_can_rescue) || d_all_player_can_rescue) then {
	d_player_can_rescue = True;
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Player can rescue"]; };
};

if (d_string_player in d_can_call_drop) then {
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Player can call drops"]; };
	d_player_can_call_drop = true;
	player setVariable ["d_dropaction", player addAction [localize "MSG_DOM_ACTIONCALLDROP" call XGreyText, "client\calldrop.sqf",[],-1,false]];
} else {
	// Non leaders can call drops when they are inside a vehicle and they are in the commander place
	//call _callvecdrop;
	// Note: There is no need to add this in playerspawn.sqf since the trigger will survive the player and work directly when he's alive again.
	d_vec_drop_id = -8877;
	// This trigger is activated when the player enters a vehicle which is not a chute and he is in the driver place
	[[0,0,0], [0, 0, 0, false], ["NONE", "PRESENT", true], ["vehicle player != player && (driver (vehicle player) == player) && !((vehicle player) isKindOf 'BIS_Steerable_Parachute') && !((vehicle player) isKindOf 'ParachuteBase') && ((player call XfGetHeight) < 5)", Format["d_drop_vehicle = vehicle player;if (d_vec_drop_id == -8877) then {d_vec_drop_id = d_drop_vehicle addAction ['%1' call XGreyText, 'client\calldrop.sqf',[],-1,false]}",localize "MSG_DOM_ACTIONCALLDROP"], "if (d_vec_drop_id != -8877) then {d_drop_vehicle removeAction d_vec_drop_id;d_vec_drop_id = -8877}"]] call XfCreateTrigger;
};

d_base_trigger = createTrigger["EmptyDetector" ,d_base_array select 0];
d_base_trigger setTriggerArea [d_base_array select 1, d_base_array select 2, d_base_array select 3, false];
d_base_trigger setTriggerActivation [d_own_side_trigger, "PRESENT", true];
d_base_trigger setTriggerStatements["this", "", ""];

// special triggers for engineers
if (d_string_player in d_is_engineer) then {
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Player is an engineer"]; };
	d_eng_can_repfuel = true;
	d_engineer_trigger = createTrigger["EmptyDetector" ,d_base_array select 0];
	d_engineer_trigger setTriggerArea [d_base_array select 1, d_base_array select 2, d_base_array select 3, false];
	d_engineer_trigger setTriggerActivation [d_own_side_trigger, "PRESENT", true];
	d_engineer_trigger setTriggerStatements["!d_eng_can_repfuel && player in thislist", Format["d_eng_can_repfuel = true;'%1' call XfGlobalChat;", localize "MSG_DOM_ENGINEERRESTORED"], ""];
	
	_trigger = createTrigger["EmptyDetector" ,[0,0,0]];
	_trigger setTriggerArea [0, 0, 0, true];
	_trigger setTriggerActivation ["NONE", "PRESENT", true];
	_trigger setTriggerStatements["call x_sfunc", Format["actionID2 = player addAction ['%1' call XGreyText, 'client\repengineer_old.sqf',[],-1,false]", localize "MSG_DOM_ACTIONREPAIR"], "player removeAction actionID2"];
};

if ((d_string_player in d_is_engineer) || d_all_player_can_unflip) then {
	[[0,0,0], [0, 0, 0, false], ["NONE", "PRESENT", true], ["call xf_ffunc", Format["actionID1=player addAction ['%1' call XGreyText, 'scripts\unflipVehicle.sqf',[dm_objectID1],-1,false];", localize "MSG_DOM_ACTIONUNFLIP"], "player removeAction actionID1"]] call XfCreateTrigger;
};

// Enemy at base
"enemy_base" setMarkerPosLocal (d_base_array select 0);	
[d_base_array select 0, [d_base_array select 1, d_base_array select 2, d_base_array select 3, true], [d_enemy_side, "PRESENT", true], ["'Man' countType thislist > 0 || 'Tank' countType thislist > 0 || 'Car' countType thislist > 0", "[0] call XBaseEnemies;'enemy_base' setMarkerSizeLocal [d_base_array select 1,d_base_array select 2];", "[1] call XBaseEnemies;'enemy_base' setMarkerSizeLocal [0,0];"]] call XfCreateTrigger;

[getPos FLAG_BASE, [400, 400, 0, false], [d_enemy_side, "PRESENT", true], ["'Man' countType thislist > 0 || 'Tank' countType thislist > 0 || 'Car' countType thislist > 0", format["hint '%1'", localize "MSG_DOM_BASEENEMYNEAR"], ""]] call XfCreateTrigger;

if (WithEmulatedFLIR) then { execFSM "fsms\Flir.fsm"; };

if (d_bag_fences_per_player > 0) then {
	player setVariable ["d_bagfenceaction_round", player addAction [localize "MSG_DOM_ACTIONROUNDFENCE" call XGreenText, "client\bagfence.sqf","ROUND",-1,false]];
	player setVariable ["d_bagfenceaction_short", player addAction [localize "MSG_DOM_ACTIONSHORTFENCE" call XGreenText, "client\bagfence.sqf","SHORT",-1,false]];
	if (d_string_player in d_is_engineer) then {
		player setVariable ["d_bagfenceaction_short", player addAction [localize "MSG_DOM_ACTIONHBARRIER" call XGreenText, "client\bagfence.sqf","CUBE",-1,false]];
		d_bag_fences_per_player = 2 * d_bag_fences_per_player;
	};
	player setVariable ["d_bagfences", 0];
};

d_player_is_medic = false;
if (d_string_player in d_is_medic) then {
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Player is a medic"]; };
	d_player_is_medic = true;
	player setVariable ["d_medicaction", player addAction [localize "MSG_DOM_ACTIONBUILDMASH" call XGreyText, "client\mash.sqf",[],-1,false]];
	player setVariable ["d_medtent", []];
	player setVariable ["d_medtent_available",d_max_mashes_per_game];
};

d_player_can_build_mgnest = false;
if (d_with_mgnest And (d_max_mgnest_per_game != 0)) then {
	if (d_string_player in d_can_use_mgnests) then {
		if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Player can build mgnests"]; };
		d_player_can_build_mgnest = true;
		player setVariable ["d_mgnest_pos", []];
		player setVariable ["d_mgnestaction", player addAction [localize "MSG_DOM_ACTIONBUILDMGNEST" call XGreyText, "client\mgnest.sqf",[],-1,false]];
		player setVariable ["d_mgnest_available", d_max_mgnest_per_game];
	};
};

d_player_can_build_aapod = false;
if (d_with_aapod And (d_max_aapod_per_game != 0)) then {
	if (d_string_player in d_can_use_aapods) then {
		if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Player can build aapods"]; };
		d_player_can_build_aapod = true;
		player setVariable ["d_aapod_pos", []];
		player setVariable ["d_aapodaction", player addAction [localize "MSG_DOM_ACTIONBUILDAA" call XGreyText, "client\aapod.sqf",[],-1,false]];
		player setVariable ["d_aapod_available", d_max_aapod_per_game];
	};
};

if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Starting to execute marker.sqf"]; };
execVM "client\marker.sqf";

// We spawn a thread to update the markers
if (!d_dont_show_vehicle_markers_at_all) then {
	[] spawn {
			while {true} do {
				[] call X_XMarkerVehicles;
				sleep 2.568;
				// No need to update the markers if the player is dead, he doesn't have access to the map anyway.
				waituntil {alive player; };
			};
		};
};

// We spawn a thread to update the markers
if (!d_dont_show_player_markers_at_all) then {
	[] spawn {
			while {true} do {
				[] call X_XMarkerPlayers;
				sleep 2.123;
				// No need to update the markers if the player is dead, he doesn't have access to the map anyway.
				waituntil {alive player; };
			};
		};
};

if (d_string_player == "test_char") then {
	// player addaction ["Generate RoadBlock" call XGreyText,"server\roadblock_test.sqf",[1],10,False,True,"","true"];
	// player addaction ["Generate Camp" call XGreyText,"server\randcamp_test.sqf",[1],10,False,True,"","true"];
	player addaction ["Record Position" call XGreyText,"client\record_position.sqf",[],10,False,True,"","true"];
};

execVM "client\playernamehud.sqf";

// This action is to allow HALO Jumps from vehicles.
//player addAction ["HALO Jump" call XGreyText,"client\halo.sqf",[],-1,false,true,"","((vehicle player != player) && (((vehicle player) call XfGetHeight) > 200))"];
//player addAction ["HALO Jump" call XGreyText,"client\halo.sqf",[],-1,false,true,"","vehicle player != player"];
d_vec_halo_id = -8977;
// This trigger is activated when the player is inside a flying vehicle and he is above ground
[[0,0,0], [0, 0, 0, false], ["NONE", "PRESENT", true], ["vehicle player != player && (((vehicle player) call XfGetHeight) >= HALOJumpMinimumHeight) && !((vehicle player) isKindOf 'BIS_Steerable_Parachute') && !((vehicle player) isKindOf 'ParachuteBase')", Format["d_halo_vehicle = vehicle player;if (d_vec_halo_id == -8977) then {d_vec_halo_id = d_halo_vehicle addAction ['%1' call XGreyText, 'client\halo.sqf',[],-1,false]}", localize "MSG_DOM_VECHALOJUMP"], "if (d_vec_halo_id != -8977) then {d_halo_vehicle removeAction d_vec_halo_id;d_vec_halo_id = -8977}"]] call XfCreateTrigger;

// In i_client.sqf you can define additional menus the player would have if the player is of a given type (MG, Medic, Leader, etc.)
if (!isNil "d_action_menus_type") then {
	if (count d_action_menus_type > 0) then {
		{
			_types = _x select 0;
			if (count _types > 0) then {
				if (_type in _types) then { 
					_action = player addAction [(_x select 1) call XGreyText,_x select 2,[],-1,false];
					_x set [3, _action];
				};
			} else {
				_action = player addAction [(_x select 1) call XGreyText,_x select 2,[],-1,false];
				_x set [3, _action];
			};
		} forEach d_action_menus_type;
	};
};
// In i_client.sqf you can define additional menus the player would have if the player is a particular unit (Medic1, Leader1, etc)
if (!isNil "d_action_menus_unit") then {
	if (count d_action_menus_unit > 0) then {
		{
			_types = _x select 0;
			_ar = _x;
			if (count _types > 0) then {
				{
					private "_pc";
					_pc = missionNamespace getVariable _x;
					if (player ==  _pc) exitWith { 
						_action = player addAction [(_ar select 1) call XGreyText,_ar select 2,[],-1,false];
						_ar set [3, _action];
					};
				} forEach _types
			} else {
				_action = player addAction [(_x select 1) call XGreyText,_x select 2,[],-1,false];
				_x set [3, _action];
			};
		} forEach d_action_menus_unit;
	};
};
// In i_client.sqf you can define additional menus on vehicles, accessible to players
if (!isNil "d_action_menus_vehicle") then {
	if (count d_action_menus_vehicle > 0) then {execVM "client\x_vecmenus.sqf"};
};

if (d_string_player in d_is_engineer) then {
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Spawning factories"];  };
	if ((["d_jet_serviceH",False] call XNetGetJIP) && !(["d_jet_s_reb",False] call XNetGetJIP)) then {
		[0] spawn XFacAction;
	};
	if ((["d_chopper_serviceH",False] call XNetGetJIP) && !(["d_chopper_s_reb",False] call XNetGetJIP)) then {
		[1] spawn XFacAction;
	};
	if ((["d_wreck_repairH",False] call XNetGetJIP) && !(["d_wreck_s_reb",False] call XNetGetJIP)) then {
		[2] spawn XFacAction;
	};
};

// Radio trigger to fix the head bug
//[[0,0,0], [0, 0, 0, false], ["JULIET", "PRESENT", true], ["this", "player call XsFixHeadBug", ""],"Fix Head Bug"] call XfCreateTrigger;


#define __facset _pos = _element select 0;\
_dir = _element select 1;\
_fac = "Land_budova2_ruins" createVehicleLocal _pos;\
_fac setDir _dir
if ((["d_jet_serviceH",False] call XNetGetJIP) && !(["d_jet_s_reb",False] call XNetGetJIP)) then {
	_element = d_aircraft_facs select 0;
	__facset;
};
if ((["d_chopper_serviceH",False] call XNetGetJIP) && !(["d_chopper_s_reb",False] call XNetGetJIP)) then {
	_element = d_aircraft_facs select 1;
	__facset;
};

_tactionar = [localize "MSG_DOM_TELEPORT" call XGreyText,"client\teleport.sqf"];
FLAG_BASE addAction _tactionar;

If (ParaAtBase) then {
	FLAG_BASE addaction [localize "MSG_DOM_ACTIONCHOOSEPARACHUTE" call XGreyText,"client\paraj.sqf"];
	_s = localize "MSG_DOM_MRKTELEPORTER";
	_s setMarkerTextLocal _s;
};

if (!isNil "LHD_Center") then {
	[] spawn {
		waituntil {typename (["LHD_Teleporter_Landing",False] call XNetGetJIP) != "BOOLEAN"};
		_lhd = ["LHD_Teleporter_Landing",ObjNull] call XNetGetJIP;
		If (!isNull _lhd) then {
			_lhd addAction [localize "MSG_DOM_TELEPORT" call XGreyText,"client\teleport.sqf"];
			if (ParaAtBase) then {
				_lhd addaction [localize "MSG_DOM_ACTIONCHOOSEPARACHUTE" call XGreyText,"client\paraj.sqf"];
			};
			_elevators = [];
			_elevator = ["LHD_Elevator_1",objNull] call XNetGetJIP;
			_id = player addAction [localize "MSG_DOM_LOWERELEVATOR", "client\lhdelevator.sqf", [_elevator,0], 1, True, False, "", "(((getPosASL (['LHD_Elevator_1'] call XNetGetJIP)) select 2) > -10) && (([player,(['LHD_Elevator_1_pos'] call XNetGetJIP)] call XfDistTo) < 15)"];
			_elevators set [0,_id];
			_id = player addAction [localize "MSG_DOM_RAISEELEVATOR", "client\lhdelevator.sqf", [_elevator,1], 1, True, False, "", "(((getPosASL (['LHD_Elevator_1'] call XNetGetJIP)) select 2) < -4) && (([player,(['LHD_Elevator_1_pos'] call XNetGetJIP)] call XfDistTo) < 15)"];
			_elevators set [1,_id];
			_elevator = ["LHD_Elevator_2",objNull] call XNetGetJIP;
			_id = player addAction [localize "MSG_DOM_LOWERELEVATOR", "client\lhdelevator.sqf", [_elevator,0], 1, True, False, "", "(((getPosASL (['LHD_Elevator_2'] call XNetGetJIP)) select 2) > -10) && (([player,(['LHD_Elevator_2_pos'] call XNetGetJIP)] call XfDistTo) < 15)"];
			_elevators set [2,_id];
			_id = player addAction [localize "MSG_DOM_RAISEELEVATOR", "client\lhdelevator.sqf", [_elevator,1], 1, True, False, "", "(((getPosASL (['LHD_Elevator_2'] call XNetGetJIP)) select 2) < -4) && (([player,(['LHD_Elevator_2_pos'] call XNetGetJIP)] call XfDistTo) < 15)"];
			_elevators set [3,_id];
			player setVariable ["elevators_actions",_elevators];
		};
	};
};

_flag_found = true;
_flag_count = 1;
while { _flag_found } do {
	_flag_count = _flag_count + 1;
	_flag_name = Format["FLAG_BASE_%1",_flag_count];
	if (!isnil _flag_name) then {
		_flag_object = missionNamespace getVariable _flag_name;
		_flag_object addAction [localize "MSG_DOM_TELEPORT" call XGreyText,"client\teleport.sqf"];
		[format["mrk_%1",_flag_name], getPos _flag_object, "ICON", "ColorGreen", [0.6,0.6],"",0,"hd_flag","",0.5] call XfCreateMarkerLocal;
		if (ParaAtBase) then {
			_flag_object addaction [localize "MSG_DOM_ACTIONCHOOSEPARACHUTE" call XGreyText,"client\paraj.sqf"];
		};
		// Moved to i_server.sqf
		// if (!isnil "d_mission_own_flag_texture") then {
			// _flag_object setFlagTexture d_mission_own_flag_texture;
		// };
	} else {
		_flag_found = false;
	};
};
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"setupplayer.sqf","Initialized Flags:", _flag_count - 1]; };


If ((d_string_player in d_is_radiooperator)) then {
	d_heli_taxi_available = true;
	// Removed the check for an available airtaxi. It is checked inside the dialog
	// If (WithAirTaxi) then { player addaction [localize "MSG_DOM_ACTIONCALLTAXI" call XGreyText,"client\airtaxi2.sqf",[],0,False,True,"","call XfAirTaxiAvailable;"]; };
	If (WithAirTaxi) then { player addaction [localize "MSG_DOM_ACTIONCALLTAXI" call XGreyText,"client\airtaxi2.sqf",[],0,False,True,"","true"]; };

// I had to remove this method because it prevents from zooming on the map, which is a big pain in the ...
// _trigger = createTrigger ["EmptyDetector", [0,0,0]];
// _trigger setTriggerText "Call in Air Taxi";
// _trigger setTriggerActivation ["HOTEL", "PRESENT", true];
// _trigger setTriggerStatements ["this", "xhandle = [] execVM ""client\airtaxi2.sqf""",""];
};

d_vec_end_time = -1;

if (isMultiplayer) then {
	[] spawn {
		sleep (0.5 + random 2);
		["d_p_varn", [getPlayerUID player,d_string_player]] call XNetCallEvent;
	};
};

"BIS_clouds_Logic" createVehicleLocal (position player);

_d_dam = (["d_dam",[]] call XNetGetJIP);
if (d_global_debug > 0) then { diag_log Format["d_dam : %1", _d_dam]; };
if (count _d_dam > 0) then {{_x allowDamage false} forEach _d_dam};

d_player_spawn_started = false;

execFSM "fsms\IsAdmin.fsm";

player addAction [localize "MSG_DOM_ACTIONSHOWSTATUS" call XLightGreenText, "client\showstatus.sqf", [],1,False,True,"","true"];

if (!isnil "d_backpacks_stack" && ((requiredVersion "1.59") || !(CurrentWorld in ["\ca\chernarus\chernarus.wrp","\ca\utes\utes.wrp"])) ) then {
	if (count d_backpacks_stack > 0) then {
		diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"setupplayer.sqf","Backpack Stack creation", d_backpacks_stack];
		_first_elem = (d_backpacks_stack select 0);
		if (count _first_elem <= 2) then {
			{
				_backpack_stack = "Misc_Backpackheap_EP1" createVehicleLocal (_x select 0);
				_backpack_stack setDir (_x select 1);
				_backpack_stack setPos (_x select 0);
				_backpack_stack setVariable ["ARTY_N_LOG_IGNORE_OBJECT",true];
				player reveal _backpack_stack;
				_backpack_stack allowdamage False;
				if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"setupplayer.sqf","Backpack Stack created at", getPos _backpack_stack]; };
				_backpack_stack addaction [localize "MSG_DOM_ACTIONCHOOSEBACKPACK" call XGreyText,"client\getbackpack.sqf"];
			} foreach d_backpacks_stack;
		} else {
			_backpack_stack = "Misc_Backpackheap_EP1" createVehicleLocal (d_backpacks_stack select 0);
			_backpack_stack setDir (d_backpacks_stack select 1);
			_backpack_stack setPos (d_backpacks_stack select 0);
			_backpack_stack setVariable ["ARTY_N_LOG_IGNORE_OBJECT",true];
			player reveal _backpack_stack;
			_backpack_stack allowdamage False;
			if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"setupplayer.sqf","Backpack Stack created at", getPos _backpack_stack]; };
			_backpack_stack addaction [localize "MSG_DOM_ACTIONCHOOSEBACKPACK" call XGreyText,"client\getbackpack.sqf"];
		};
	} else {
		diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"setupplayer.sqf","No backpacks: d_backpacks_stack is empty", d_backpacks_stack];
	};
} else {
	if (isnil "d_backpacks_stack") then {
		diag_log Format["(%1)[%2]: %3",diag_tickTime,"setupplayer.sqf","No backpacks: d_backpacks_stack not defined"];}
	else {
		if (count d_backpacks_stack <= 0) then {
			diag_log Format["(%1)[%2]: %3",diag_tickTime,"setupplayer.sqf","No backpacks: d_backpacks_stack is empty"];}
		else {
			if (!requiredVersion "1.59") then {
				diag_log Format["(%1)[%2]: %3",diag_tickTime,"setupplayer.sqf","No backpacks: Invalid version"];
			} else {
				diag_log Format["(%1)[%2]: %3 %4",diag_tickTime,"setupplayer.sqf","No backpacks: Unknown",[(CurrentWorld in [d_backpacks_stack, requiredVersion "1.59", "\ca\chernarus\chernarus.wrp","\ca\utes\utes.wrp"])]];
			};
		};
	};
};

player SetVariable ["d_pbp_id", -9999];
d_backpack_helper = [];
player SetVariable ["d_custom_backpack", []];
player SetVariable ["d_player_backpack", []];
if (WithBackpack) then {
	d_prim_weap_player = primaryWeapon player;
	_s = format [localize "MSG_DOM_ACTIONBACKPACKTO", [d_prim_weap_player,1] call XfGetDisplayName];
	if (d_prim_weap_player != "" && d_prim_weap_player != " ") then {
		player SetVariable ["d_pbp_id",player addAction [_s call XGreyText, "client\backpack.sqf",[],-1,false]];
	};
	
	XfBackpackActionFix = {
		d_prim_weap_player = primaryWeapon player;
		_id = player getVariable "d_pbp_id";
		if (_id != -9999 || count (player getVariable "d_player_backpack") == 0) then {
			if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"XfBackpackActionFix","Removing",_id,count (player getVariable "d_player_backpack")]; };
			player removeAction _id;
			player setVariable ["d_pbp_id", -9999];
		};
		if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3: %4 %5 %6",diag_tickTime,"XfBackpackActionFix","Adding",(player getVariable "d_pbp_id"),count (player getVariable "d_player_backpack"),d_prim_weap_player]; };
		if ((player getVariable "d_pbp_id" == -9999) && count (player getVariable "d_player_backpack") == 0 && d_prim_weap_player != "" && d_prim_weap_player != " ") then {
			player setVariable ["d_pbp_id", player addAction [format [localize "MSG_DOM_ACTIONBACKPACKTO", [d_prim_weap_player,1] call XfGetDisplayName] call XGreyText, "client\backpack.sqf",[],-1,false]];
		} else {
			player setVariable ["d_pbp_id", player addAction [format [localize "MSG_DOM_ACTIONBACKPACKFROM", [(player getVariable "d_player_backpack") select 0,1] call XfGetDisplayName] call XGreyText, "client\backpack.sqf",[],-1,false]];
		};
	};
	// No Weapon fix for backpack
	[[0,0,0], [0, 0, 0, false], ["NONE", "PRESENT", true], ["primaryWeapon player != d_prim_weap_player && primaryWeapon player != '' && primaryWeapon player != ' '","call XfBackpackActionFix",""]] call XfCreateTrigger;
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Backpack Added"]; };
	
	// The following is a safety check which will control is there is a backpack content en if an action exists for this backpack.
	// Otherwise it adds an action back. This is a safety check.
	// [] spawn {
		// while {true} do {
			// sleep 15.572;
			// if (alive player) then {
			
			// };
		// };
	// };
};

If (count d_pos_ai_hut > 0) then {
	[] spawn {
		private ["_ai"];
		_ai = objNull;
		while { isNull _ai } do {
			_ai = ["D_AI_HALO_OFFICER",objNull] call XNetGetJIP;
			sleep 1.645;
		};
		
		_ai = ["D_AI_HALO_OFFICER",objNull] call XNetGetJIP;
		_id = _ai addAction [localize "MSG_DOM_REQUESTHALO", "client\halorequest.sqf", [], 1, True, False, "", "true"];
		_ai setVariable ["request_action_id", _id];
		_ai = ["D_AI_GROUP_OFFICER",objNull] call XNetGetJIP;
		_id = _ai addAction [localize "MSG_DOM_REQUESTGROUP", "client\grouprequest.sqf", [], 1, True, False, "", "true"];
		_ai setVariable ["request_action_id", _id];
	};
};

if (d_global_debug > 5) then { 
	diag_log Format["JIPH mr1_in_air %1",(["mr1_in_air","empty"] call XNetGetJIP)];
	diag_log Format["JIPH mr2_in_air %1",(["mr2_in_air","empty"] call XNetGetJIP)];
	diag_log Format["JIPH ammo_boxes %1",(["ammo_boxes","empty"] call XNetGetJIP)];
	diag_log Format["JIPH sec_kind %1",(["sec_kind","empty"] call XNetGetJIP)];
	diag_log Format["JIPH d_ammo_boxes %1",(["d_ammo_boxes","empty"] call XNetGetJIP)];
	diag_log Format["JIPH para_available %1",(["para_available","empty"] call XNetGetJIP)];
	diag_log Format["JIPH current_target_position %1",(["current_target_position","empty"] call XNetGetJIP)];
	diag_log Format["JIPH available_drop_vehicles %1",(["available_drop_vehicles","empty"] call XNetGetJIP)];
	diag_log Format["JIPH X_DropZone %1 (%2)",(["X_DropZone","empty"] call XNetGetJIP), isNil("X_DropZone")];
	diag_log Format["JIPH X_DropZone Position %1",GetPos(["X_DropZone","empty"] call XNetGetJIP)];
	diag_log Format["JIPH G_MISSION_OBJECTS %1",["G_MISSION_OBJECTS","empty"] call XNetGetJIP];
};

if (d_string_player == "enemy_commander") then {
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Enemy commander"];  };
	onTeamSwitch {
		private ["_var"];
		_var = _from getVariable "d_ec_ts_id";
		if (!isnil "_var") then {
			_from removeAction _var;
			_from setVariable ["d_ec_ts_id",nil];
			diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"TeamSwitch","Removed Action",_from, _var];
		};
		_var = _from getVariable "d_ec_eh_id";
		if (!isnil "_var") then {
			_from removeEventHandler ["killed", _var];
			_from setVariable ["d_ec_eh_id",nil];
			diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"TeamSwitch","Removed Event",_from, _var];
		};	
		_var = _to getVariable "d_ec_ts_id";
		if (isnil "_var") then {
			_var = _to addAction ["Team Switch" call XGreyText, "client\teamswitch.sqf",[],-1,false];
			_to SetVariable ["d_ec_ts_id",_var];
			diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"TeamSwitch","Added Action",_to, _var];
		};
		_var = _to getVariable "d_ec_eh_id";
		if (isnil "_var") then {
			_var = _to addEventHandler ["killed", {_this exec "client\teamswitch.sqf"}];
			_to setVariable ["d_ec_eh_id",_var];
			diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"TeamSwitch","Added Event",_to, _var];
		};	
	};
	[] spawn {
		private ["_var","_initial_pos","_commander"];
		_commander = player;
		_initial_pos = getPos _commander;
		while { true } do {
			_var = player getVariable "d_ec_ts_id";
			if (isnil "_var") then {
				_var = player addAction ["Team Switch" call XGreyText, "client\teamswitch.sqf",[],-1,false,true,"","(player call XfIsAdmin)"];
				player SetVariable ["d_ec_ts_id",_var];
				diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"TeamSwitch","Removed Action",player, _var];
			};
			if ((_commander distance _initial_pos) > 10) then { _commander setPos _initial_pos };
			sleep 10;
		};
	};
};

execVM "missions\mission_init.sqf";

X_PLAYER_INIT = True;
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"Setupplayer.sqf","Fully executed"]; };